<template>
  <div class="common-layout">
    <el-container>
      <el-header class="common-header" style="box-shadow:var(--el-box-shadow-light);">
        <AllHead></AllHead>
      </el-header>
      <el-main>
        <div class="title">
          <!-- title盒子 -->
          <h1 class="recipeTitle">
            {{ getData.name }}
          </h1>
          <!-- 食谱名称 -->
          <el-link v-show="edit" class="edit" @click="editRecipe(getData)">编辑</el-link>
        </div>
        <!-- 图片展示 -->
        <div class="showImg">
          <div class="title-footer">
            <p>可供用餐人数：{{ getData.servings }}人</p>
            <!-- 可供用餐人数 -->
            <div class="title-icon">
              难度：<el-rate v-model.number="rate" disabled size="small" class="rate" />
              <!-- 难度星级 -->

              <!-- 点赞显示以及点赞功能 -->
              <div class="smallIcon">
                <iconify-icon icon="material-symbols:favorite-rounded" style="color: red"
                  v-show="(isLikeNum == '1') ? true : false" @click="cancelLike" />
                <iconify-icon icon="material-symbols:favorite-outline" @click="checkLike"
                  v-show="(isLikeNum == '0' || isLikeNum === '') ? true : false" />
                <span class="titletext">{{ getData.likeCount }}</span>
              </div>

              <!-- 评论显示 -->
              <div class="smallIcon">
                <el-icon>
                  <ChatLineRound />
                </el-icon>
                <span class="titletext">{{ getData.commentCount }}</span>
              </div>

              <!-- 收藏显示以及收藏功能 空为未收藏 黑为公开收藏 蓝为私人收藏 -->
              <div class="smallIcon">
                <iconify-icon @click="cancelCollect" v-show="(isCollectNum == '0') ? true : false"
                  icon="pepicons-pop:star-filled" class="titletext" style="color: yellow" />
                <iconify-icon @click="checkCollect" v-show="(isCollectNum == '1' || isCollectNum === '') ? true : false"
                  icon="pepicons-pop:star" style="color: #0b0b0b" />
                <span>{{ getData.collectCount }}</span>
              </div>
              <el-dialog v-model="centerDialogVisible" title="选择收藏文件夹" width="500" center>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button class="!ml-0" plain @click="open1(1)">私人文件夹</el-button>
                    <el-button type="primary" class="!ml-0" plain @click="open1(2)">公开文件夹</el-button>
                  </div>
                </template>
              </el-dialog>
            </div>
          </div>


          <!-- 封面图片 -->
          <el-image style=" height: 30vw" :src="coverUrl" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" show-progress
            :initial-index="0" fit="cover" :preview-src-list="coverSrcList" />
          <br>
          <el-tag type="danger" round size="large">热门</el-tag><el-tag type="success" round size="large">营养</el-tag>
        </div>


        <!-- 食谱作者信息 -->
        <div class="author">
          <el-image :src="coverUrl" class="userImg"></el-image>
          <div class="authorName"><el-link underline="never">{{ getData.author.nickname }}</el-link></div>
          <div class="authorFan">粉丝：{{ getData.author.fansCount }}</div>
          <el-button class="authorFollow" type="primary" @click="confirmFollow" v-show="follow1">关注</el-button>
          <el-button class="authorFollow" plain @click="cancelFollow" v-show="follow2">已关注</el-button>
        </div>

        <!-- 食谱描述 -->
        <div class="describe">
          <p class="describe-header">作者描述：</p>
          <div class="describe-p">{{ getData.description }}</div>
        </div>

        <!-- 所需厨具 -->
        <div class="cooker">
          所需厨具： <el-tag type="primary" effect="plain" size="large" v-for="i in getData.cookerList" class="cooker-tag">{{
            i.name }}×{{ i.quantity }}</el-tag>
        </div>
        <!-- 所需食材 -->

        <div class="food">
          所需食材： <el-tag type="primary" effect="plain" size="large" v-for="j in getData.materialList" class="food-tag">{{
            j.name }}({{ materialCategory[j.category].label }}×{{
              j.quantity }}{{ materialUnit[j.unit].label }})</el-tag>
        </div>

        <!-- 步骤展示 -->
        <div class="step">
          <div class="step-p" v-for="(k, index) in getData.cookingList">
            <p>步骤{{ index + 1 }}：{{ k.title }}</p>
            <div>{{ k.description }}</div>
          </div>
          <img src="" alt="">

        </div>
        <div class="comment">
          <RecipeComment :recipeId="recipeId"></RecipeComment>
        </div>

      </el-main>
      <!-- 网页footer -->
      <el-footer class="footer">
        <hr>
        <p class="footer-p">
          <a href="#"> 关于我们 |</a>
          <a href="#"> 帮助中心 |</a>
          <a href="#"> 客服咨询 |</a>
          <a href="#"> 食材采购 |</a>
          <a href="#"> 商业合作 |</a>
          <a href="#"> 友情链接</a>
        </p>
      </el-footer>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, toRefs, reactive } from 'vue';
import AllHead from './AllHead.vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import RecipeComment from '../ShowRecipe/RecipeComment.vue';
import router from '@/router';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import { fa } from 'element-plus/es/locale/index.mjs';
let route = useRoute()
// 使用toRefs包裹使得所有数据都扔保留响应式
let { query } = toRefs(route)//解构出query方法，直接使用
// defineProps(['recipeId'])//现在不用这个，因为需要用到值
console.log(query.value);

let recipeId = ref(query.value.recipeId)//通过路由query传值得到主页的所点击的食谱id

let userId = ref(sessionStorage.getItem('userId'))
console.log(userId.value);

console.log('userId' + userId.value);

// 收藏接口以及reactive
interface showCollectData {
  id: number,
  isDeleted: string
}
let getCollectData: showCollectData = reactive({
  id: -1,
  isDeleted: ''
})

// 点赞接口以及reactive
interface showLikeData {
  id: number,
  isLiked: string
}
let getLikeData: showLikeData = reactive({
  id: -1,
  isLiked: ''
})

interface showFollowData {
  fanId: number,
  id: any,
  idolId: number,
  isBlocked: string
}
let getFollowData: showFollowData = reactive({
  fanId: -1,
  id: null,
  idolId: -1,
  isBlocked: '1'
})

//食谱数据接口
interface showData {
  author: author
  boardId: number
  collectCount: number
  commentCount: number
  cookerList: cookerList[]
  cookingList: cookingList[]
  coverImage: string
  createTime: string
  description: string
  difficulty: number
  id: number
  likeCount: number
  materialList: materialList[]
  name: string
  servings: string
  tips: string
  userId: number
}
//作者信息接口
interface author {
  avatarUrl: string
  bio: string
  fansCount: number
  id: number
  isAdmin: string
  nickname: string
  recipeCount: number
}
//厨具接口
interface cookerList {
  id: number
  name: string
  quantity: number
  recipeId: number
}
//步骤接口
interface cookingList {
  description: string
  id: number
  imageUrl: string
  recipeId: number
  stepNumber: number
  timeRequired: number
  timeUnit: string
  title: string
}
//材料接口
interface materialList {
  category: number
  id: number
  name: string
  quantity: number
  recipeId: number
  unit: number
}
//食谱数据的reactive
let getData: showData = reactive({
  author: {
    avatarUrl: '',
    bio: '',
    fansCount: 0,
    id: 0,
    isAdmin: '',
    nickname: '',
    recipeCount: 0
  },
  boardId: 0,
  collectCount: 0,
  commentCount: 0,
  cookerList: [{
    id: 0,
    name: '',
    quantity: 0,
    recipeId: 0,
  }],
  cookingList: [{
    description: '',
    id: 0,
    imageUrl: '',
    recipeId: 0,
    stepNumber: 0,
    timeRequired: 0,
    timeUnit: '',
    title: '',
  }],
  coverImage: '',
  createTime: '',
  description: '',
  difficulty: 0,
  id: 0,
  likeCount: 0,
  materialList: [{
    category: 0,
    id: 0,
    name: '',
    quantity: 0,
    recipeId: 0,
    unit: 0
  }],
  name: '',
  servings: '',
  tips: '',
  userId: 0
})

//材料数量的枚举
const materialUnit = [
  {
    label: '',
    value: 0
  },
  {
    label: '克',
    value: 1
  },
  {
    label: '千克',
    value: 2
  },
  {
    label: '毫升',
    value: 3
  },
  {
    label: '升',
    value: 4
  }
]
//材料种类的枚举
const materialCategory = [
  {
    label: '',
    value: 0
  },
  {
    label: '主料',
    value: 1
  }, {
    label: '辅料',
    value: 2
  },
  {
    label: '调料',
    value: 3
  }
]
let edit = ref(false)
let rate: number
let isLikeNum = ref('')
let isCollectNum = ref('')
let collectId: number
let likeId: number
let followId: number
let coverUrl = getData.coverImage
const coverSrcList = getData.coverImage


let follow1 = ref(false)
let follow2 = ref(false)
//当进入这个页面时执行dataForm并得到食谱数据进行展示
dataForm()
async function dataForm() {
  const dataAxios = await axios({
    url: '/api/recipe/getRecipeDetail',
    params: {
      recipeId: recipeId.value
    },
    headers: { 'content-type': 'application/json' }
  })

  // 查询食谱点赞情况
  const likeAxios = await axios({
    url: '/api/like/getLikeRecipeRecord',
    params: {
      recipeId: recipeId.value
    },
    headers: { 'content-type': 'application/json' }
  })

  // 查询食谱收藏情况
  const collectAxios = await axios({
    url: '/api/collection/getCollectionRecord',
    params: {
      recipeId: recipeId.value
    },
    headers: { 'content-type': 'application/json' }
  })
  // 获取点赞数据(以getLikeData接收)
  Object.assign(getLikeData, likeAxios.data.data)
  isLikeNum.value = getLikeData.isLiked
  likeId = getLikeData.id
  // 获取收藏数据(以getCollectData接收)
  Object.assign(getCollectData, collectAxios.data.data)

  isCollectNum.value = getCollectData.isDeleted
  collectId = getCollectData.id
  console.log(isCollectNum.value);

  // 获取食谱数据(以getData接收)
  Object.assign(getData, dataAxios.data.data)
  if (Number(getData.author.id) == Number(userId.value)) {
    follow1.value = false
    follow2.value = false
    console.log('同一个人');

  } else {

    console.log('不同');

    // 获取用户对食谱作者的关注情况
    const followAxios = await axios({
      url: '/api/society/queryFollowInfo',
      params: {
        idolId: getData.author.id
      },
      headers: { 'content-type': 'application/json' }
    })
    Object.assign(getFollowData, followAxios.data.data)
    console.log(getFollowData);
    followId = getFollowData.id
    if (getFollowData.isBlocked == '1') {
      follow1.value = true
      follow2.value = false
    } else {
      follow1.value = false
      follow2.value = true
    }

  }
  console.log(getData.author.id);
  console.log(userId.value);


  //获取食谱数据中的难度
  rate = getData.difficulty
  // console.log(likeAxios.data);

  console.log(isLikeNum.value === '');
  const currentUserId = Number(userId.value);
  edit.value = !isNaN(currentUserId) && currentUserId === getData.author.id;
}


let JsonFollow
// 确认关注
async function confirmFollow() {
  if (followId == null) {
    JsonFollow = reactive({
      id: null,
      idolId: getData.author.id,
      isBlocked: '0'
    })
  } else {
    JsonFollow = reactive({
      id: followId,
      idolId: getData.author.id,
      isBlocked: '0'
    })
  }
  const followAxios = await axios({
    url: '/api/society/followOrNot',
    method: 'post',
    data: JSON.stringify(JsonFollow),
    headers: { 'content-type': 'application/json' }
  })
  Object.assign(JsonFollow, followAxios.data.data)
  // console.log(JsonFollow);

  followId = Number(JsonFollow.id)
  // console.log(followId);
  console.log(JsonFollow.isBlocked);


  // 转换是否关注按钮
  follow1.value = false
  follow2.value = true
  getData.author.fansCount++

}

// 取消关注
async function cancelFollow() {
  JsonFollow = reactive({
    id: followId,
    idolId: getData.author.id,
    isBlocked: '1'
  })
  const followAxios = await axios({
    url: '/api/society/followOrNot',
    method: 'post',
    data: JSON.stringify(JsonFollow),
    headers: { 'content-type': 'application/json' }
  })
  Object.assign(JsonFollow, followAxios.data.data)

  followId = Number(JsonFollow.id)
  console.log(JsonFollow.isBlocked);
  
  follow1.value = true
  follow2.value = false
  getData.author.fansCount--
}





let JsonLike
JsonLike = reactive({
  id: getLikeData.id,
  isLiked: isLikeNum,
  recipeId: recipeId,
})
let sendLikeAxios: any
//点赞的axios

//确认点赞
async function checkLike() {
  if (isLikeNum.value === '') {
    JsonLike = reactive({
      id: null,
      isLiked: 1,
      recipeId: recipeId,
    })
    // 用户第一次点赞请求完需要获取点赞id
    await axios({
      url: '/api/like/thumbsUpRecipe',
      method: 'post',
      data: JSON.stringify(JsonLike),
      headers: { 'Content-Type': 'application/json' }
    })
    const likeAxios = await axios({
      url: '/api/like/getLikeRecipeRecord',
      params: {
        recipeId: recipeId.value
      },
      headers: { 'content-type': 'application/json' }
    })
    Object.assign(getLikeData, likeAxios.data.data)
    isLikeNum.value = '1'
    getData.likeCount++
    likeId = getLikeData.id
  } else {
    JsonLike = reactive({
      id: likeId,
      isLiked: 1,
      recipeId: recipeId,
    })
    await axios({
      url: '/api/like/thumbsUpRecipe',
      method: 'post',
      data: JSON.stringify(JsonLike),
      headers: { 'Content-Type': 'application/json' }
    })
    isLikeNum.value = '1'
    getData.likeCount++
  }
}

// 取消收藏
async function cancelLike() {
  JsonLike = reactive({
    id: likeId,
    isLiked: 0,
    recipeId: recipeId,
  })
  await axios({
    url: '/api/like/thumbsUpRecipe',
    method: 'post',
    data: JSON.stringify(JsonLike),
    headers: { 'Content-Type': 'application/json' }
  })
  isLikeNum.value = '0'
  getData.likeCount--
}







const centerDialogVisible = ref(false)//收藏选择框
let JsonCollect

// 点击收藏，显示选择框
function checkCollect() {
  centerDialogVisible.value = true
}

// 选择收藏夹
async function open1(index: number) {
  // 判断用户是否成功收藏过
  if (isCollectNum.value === '') {
    if(index == 1){
      JsonCollect = reactive({
        id: null,
        isBlocked: 1,
        isDeleted: 0,
        recipeId: recipeId.value
      })
    }else{
      JsonCollect = reactive({
        id: null,
        isBlocked: 0,
        isDeleted: 0,
        recipeId: recipeId.value
      })
    }
    // 如果是第一次发送收藏请求需要接着查询食谱收藏情况获取收藏后的id
    await axios({
      url: 'api/collection/collect',
      method: 'post',
      data: JSON.stringify(JsonCollect),
      headers: { 'Content-Type': 'application/json' }
    })

    const collectAxios = await axios({
      url: '/api/collection/getCollectionRecord',
      params: {
        recipeId: recipeId.value
      },
      headers: { 'content-type': 'application/json' }
    })
    // 获取收藏情况(以getCollectData接收)
    Object.assign(getCollectData, collectAxios.data.data)
    isCollectNum.value = '0'//判断是否收藏图标
    getData.collectCount++//展示给用户看的

    // 取消展示框
    centerDialogVisible.value = false
    showCollect(index)
    collectId = getCollectData.id//获取收藏id
    return

  } else if (index == 1) {
    JsonCollect = reactive({
      id: collectId,
      isBlocked: 1,
      isDeleted: 0,
      recipeId: recipeId.value
    })
  } else {
    JsonCollect = reactive({
      id: collectId,
      isBlocked: 0,
      isDeleted: 0,
      recipeId: recipeId.value
    })
  }
  // 发送收藏请求
  await axios({
    url: '/api/collection/collect',
    method: 'post',
    data: JSON.stringify(JsonCollect),
    headers: { 'Content-Type': 'application/json' }
  })
  isCollectNum.value = '0'//判断是否收藏图标
  getData.collectCount++//展示给用户看的

  // 取消展示框
  centerDialogVisible.value = false
  showCollect(index)
}


// 取消收藏
async function cancelCollect() {

  JsonCollect = reactive({
    id: collectId,
    isBlocked: null,
    isDeleted: 1,
    recipeId: recipeId.value
  })
  // 发送取消收藏请求
  await axios({
    url: '/api/collection/collect',
    method: 'post',
    data: JSON.stringify(JsonCollect),
    headers: { 'Content-Type': 'application/json' }
  })
  isCollectNum.value = '1'
  getData.collectCount--

}

function showCollect(index:number){
  if(index == 1){
  ElNotification({
      title: '收藏成功',
      message: '已收藏入私人文件夹',
      type: 'success',
    })
  }else{
    ElNotification({
      title: '收藏成功',
      message: '已收藏入公开文件夹',
      type: 'success',
    })
  }
}



function editRecipe(recipeData: showData) {
  router.push({
    path: 'createcook',
    query: { recipeId: recipeId.value }
  })
}
</script>

<style scoped>
.food-tag,
.cooker-tag {
  margin-right: 8px
}

.describe-header {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

/* .describe-p {
  color: #666;
  line-height: 1.6;
  font-size: 18px;
} */

.redlike {
  position: absolute;
  top: 3.5px;
}

.smallIcon {
  display: inline-block;
  font-size: 12px;
  width: 80px;

}

.titletext {
  user-select: none;
}

.title-icon {
  /* padding-left: 60%;
   */
  position: absolute;
  right: 0;
  top: -10px;
}


.title {
  height: 100px;
}

.recipeTitle {
  font-size: 30px;
}

.edit {
  float: right;
}

h2 {
  display: inline-block;
  margin: 0;
  padding: 0;
}

.el-main {
  position: relative;
  top: 10vh;
  padding: 50px 20vw;
  background-color: #FFFCF5;
  background-image: linear-gradient(to bottom, #FFFCF5, #FFF9F0);
}

.common-header {
  position: fixed;
  z-index: 999;
  height: 10vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #FFFCF5;
  /* background-color: rgb(191, 227, 241); */
}

.userImg {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  float: left;
}

.authorName {
  position: absolute;
  left: 80px;
  top: 5px;
  height: 50px;
  display: inline-block;
  line-height: 50px;
  margin-left: 10px;
}

.authorFan {
  position: absolute;
  left: 98px;
  top: 60px;
  font-size: 12px;
  color: #333;
}

.author {
  position: relative;
  padding: 16px;
  margin: 20px 0;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.author:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.authorFollow {
  margin-left: 100px;
}

.userImg {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f8f8f8;
}

.authorName {
  margin-left: 16px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.authorName .el-link {
  font-size: inherit;
  color: inherit;
}

.showImg {
  position: relative;
}

.showImg .el-image {
  width: 100%;
  object-fit: cover;
  border-radius: 2vw;
  margin-bottom: 3vw;
}

.showImg .el-tag {
  margin-top: 10px;
  margin-right: 8px;
  width: 60px;
  transition: all 0.3s ease;
}

.showImg .el-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.describe {
  margin: 20px 0;
  padding: 16px;
  background: #FFF9F2;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #FFE8CC;
}

.cooker {
  margin: 20px 0;
  padding: 16px;
  background: #F8F5FF;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #E6DDFF;
}

.food {
  margin: 20px 0;
  padding: 16px;
  background: #F2FFF5;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #CCFFDD;
}

.cooker-tag,
.food-tag {
  margin: 8px;
  transition: all 0.3s ease;
}

.cooker-tag:hover,
.food-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.step {
  margin: 20px 0;
  padding: 16px;
  background: #FFF2F2;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #FFCCCC;
}

.step-p {
  margin: 16px 0;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.step-p div {

  word-break: break-all;
}

.step-p:last-child {
  border-bottom: none;
}

.step-p p:first-child {
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.step-p p:last-child {
  color: #666;
  line-height: 1.6;
}

.el-tag:hover {
  background-color: aquamarine;
}

.footer {
  padding-left: 20vw;
  padding-right: 20vw;
  background-color: #fff;
  margin-top: 84px;
}

a {
  text-decoration: none;
  color: #333;

}

.footer-p {
  padding-left: 300px;
}
</style>
